package com.travel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.travel.domain.entity.Order;
import com.travel.service.OrderService;
import com.travel.common.Result;
import com.travel.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 查询所有订单
     */
    @GetMapping("/list")
    public Result<List<Order>> getAllOrders() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        List<Order> orders = orderService.list(wrapper);
        return Result.success(orders);
    }

    /**
     * 根据ID查询订单
     */
    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable("id") Long id) {
        Order order = orderService.getById(id);
        if (order != null) {
            return Result.success(order);
        } else {
            return Result.error("订单不存在");
        }
    }

    /**
     * 创建订单（秒杀场景）解决超卖问题
     */
    // 解决超卖问题
    @PostMapping("/create")
    public Result<String> createOrder(@RequestBody Order order) {
        Long userId = BaseContext.getCurrentId();
        order.setUserId(userId);

        String stockKey = "product:stock:" + order.getProductId(); // 缓存库存的 Key

        // 扣减库存（原子操作）
        Long stock = redisTemplate.opsForValue().decrement(stockKey,order.getQuantity());
        if (stock == null || stock < 0) {
            // 库存不足，回滚库存
            redisTemplate.opsForValue().increment(stockKey,order.getQuantity());
            return Result.error("库存不足，无法下单");
        }

        try {
            // 生成订单
            boolean result = orderService.save(order);
            if (result) {
                return Result.success("订单创建成功");
            } else {
                // 保存订单失败，回滚库存
                redisTemplate.opsForValue().increment(stockKey);
                return Result.error("订单创建失败");
            }
        } catch (Exception e) {
            // 异常处理，回滚库存
            redisTemplate.opsForValue().increment(stockKey);
            return Result.error("系统异常，请稍后重试");
        }
    }

    /**
     * 更新订单
     */
    @PutMapping("/update")
    public Result<String> updateOrder(@RequestBody Order order) {
        Long userId = BaseContext.getCurrentId();
        order.setUserId(userId);
        boolean result = orderService.updateById(order);
        if (result) {
            return Result.success("订单更新成功");
        } else {
            return Result.error("订单更新失败");
        }
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteOrder(@PathVariable("id") Long id) {
        boolean result = orderService.removeById(id);
        if (result) {
            return Result.success("订单删除成功");
        } else {
            return Result.error("订单删除失败");
        }
    }
}
